<template>
    <!-- 供应商解除处罚 -->
    <div class="e-form">
        <div class="tabs" v-if="Object.keys(reasonFormData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="解除原因"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="解除附件"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <!-- 解除原因 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    解除原因
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="reasonFormData"
                                        label-width="150px"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="供应商名称："
                                                >
                                                    {{
                                                        reasonFormData.outerName
                                                    }}
                                                    <el-button
                                                        style="
                                                            background-color: rgb(
                                                                22,
                                                                155,
                                                                213
                                                            );
                                                            color: #fff;
                                                            margin-left: 20px;
                                                        "
                                                        >查看</el-button
                                                    >
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="统一社会信用代码："
                                                >
                                                    {{
                                                        reasonFormData.creditCode
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="供应商类型："
                                                >
                                                    {{
                                                        reasonFormData.outerTypeKey
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="解除后等级："
                                                >
                                                    {{ reasonFormData.grade }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="原处罚等级："
                                                >
                                                    {{
                                                        reasonFormData.originalGrade
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="状态：">
                                                    {{ reasonFormData.state }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="原处罚原因："
                                                >
                                                    {{ reasonFormData.remark }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="24">
                                                <el-form-item
                                                    label="解除原因："
                                                >
                                                    <el-input
                                                        type="textarea"
                                                        :rows="2"
                                                        placeholder="请输入内容"
                                                        v-model="
                                                            reasonFormData.reason
                                                        "
                                                    >
                                                    </el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                        <!-- ------------------------------------------------------------------------------------- -->
                    </div>
                    <!-- 解除附件 -->
                    <div id="WarehouseCon" class="con">
                        <div class="tabs-title" id="accessory">解除附件</div>
                        <div class="e-table">
                            <AttachComp
                                :bucketName="bucketName"
                                :relationId="billid"
                            />
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ComExaHistory
                            :billType="6047"
                            @getAuditHistory="getAuditHistory"
                            :tableData="tableData"
                            ref="ComExaHistory"
                        />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <span class="tip"
                ><span style="color: red; margin-right: 0">*</span
                >为必填项</span
            >
            <div class="buttons">
                <ComExaButtons
                    v-if="id"
                    :auditState="auditState"
                    :state="reasonFormData.state"
                    @exas="exas"
                />
                <el-button type="primary" v-else @click="newsave" size="small"
                    >保存</el-button
                >
                <el-button @click="handleClose" size="small">取消</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import subcontractorChange from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorChange.js'
import subcontractorRAP from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorRAP.js'
import examine from '@/api/OutsourcingartyAdmin/subcontractorAdmin/examine.js'
import ComExaButtons from '@/components/common/exaButtons'
//审核历史
import ComExaHistory from '@/components/common/exaHistory.vue'
import AttachComp from '@/components/common/attachIndex'
import { throttle, showSuccessPop, openAppClient, showLoading, hideLoading } from '@/utils/common'
// 作废
import { toVoid } from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractor.js'
export default {
    components: {
        ComExaHistory,
        AttachComp,
        ComExaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            bucketName: 'OutsourcingartyAdmin',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            formData: {}, //解除基本数据
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            winEvent: {}, //保存事件，跳转页面的时候，结束事件，优化性能
            auditState: {}, //按钮状态
            //解除原因表单数据
            reasonFormData: {
                outerName: '', //分包商名称
                creditCode: '', //统一社会信用代码
                outerTypeKey: '', //供应商类型
                grade: '', //解除后等级
                originalGrade: '', //原处罚等级
                remark: '', //处罚原因
                reason: '', //解除原因
                state: 0, //状态
                id: '' //主键
            },
            creditCode: '', //信用代码
            billid: '', //原单id
            id: '', //当前单据id ，用来判断流程按钮和审核
            // 审核对象
            commit: {
                billId: '', //	单据Id
                billType: 6047, //单据编码
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //	下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '' //审核意见
            }
        }
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    created () {
        // this.creditCode = this.$route.query.creditCode
        this.creditCode = this.$route.query.creditCode
        this.getData()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'accessory', 'auditHistory']
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    methods: {
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
                        document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        // 初始化惩罚数据
        async getData () {
            // 先通过信用代码查询详情，没有再通过信用代码查初始化接口
            let data = await subcontractorRAP.getCreditCodeFindByid({
                creditCode: this.creditCode
            })
            if (data.code != 200) {
                this.reasonFormData = data
                this.id = data.id
                this.getAuditHistory()
                this.getCurrentUnitInfo()
            } else {
                // 没有数据用信用代码初始化
                this.getinitializationFindByid({ creditCode: this.creditCode })
            }
        },
        // 初始化
        async getinitializationFindByid () {
            let data = await subcontractorRAP.getinitializationFindByid({
                creditCode: this.creditCode
            })
            this.reasonFormData = data
            this.id = data.id
            this.getAuditHistory()
        },
        // 新增解除惩罚
        async newsave () {
            let data = await subcontractorRAP.liftingPunishmentAdd(
                this.reasonFormData
            )
            if (data.code == 200) {
                this.getData()
            }
        },
        // 修改
        async save () {
            let data = await subcontractorRAP.liftingPunishmentUpdate(
                this.reasonFormData
            )
            if (data.code == 200) {
                this.getData()
            }
        },
        submit () {
            Promise.all([
                subcontractorRAP.liftingPunishmentUpdate(this.reasonFormData)
            ])
                .then(async () => {
                    this.commit.billId = this.id
                    subcontractorChange.findcommit(this.commit).then(() => {
                        this.clientPop('suc', '提交成功')
                        this.getData()
                    })
                })
                .catch(() => {
                    this.clientPop('err', '保存失败')
                    this.scorllError()
                })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //取消
        handleClose () {
            this.dialogVisible = false
            this.$router.push('/subcontractorAward')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        onChangeTab (e) {
            console.log('clickTabFlag: ', this.clickTabFlag)
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 审核历史列表查询
        async getAuditHistory () {
            if (this.id) {
                let data = await subcontractorChange.findByIdAuditHistory({
                    billId: this.id,
                    billType: 6047,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                this.tableData = data
            } else {
                return
            }
        },
        // 审核
        audit () {
            Promise.all([
                subcontractorRAP.liftingPunishmentUpdate(this.reasonFormData)
            ])
                .then(async () => {
                    // 客户端弹窗弹出本地页面
                    openAppClient('/exaDialog', '填写审核意见', () => {
                        // 审核拿到审核弹窗的意见
                        const auditParams = JSON.parse(
                            localStorage.vuex
                        ).auditParams
                        // 将审核意见赋值给参数传给后端
                        examine
                            .audit({
                                billId: this.id,
                                billType: 6047,
                                freeNextUnitIndex: 0,
                                freeNextUser: '',
                                isPass: auditParams.isPass,
                                isShareInAudit: true,
                                opinion: auditParams.opinion
                            })
                            .then(() => {
                                this.clientPop('suc', '审核成功')
                                this.getData()
                            })
                    }, null, null, null, 'small')
                })
                .catch(() => {
                    this.clientPop('err', '保存失败')
                    this.scorllError()
                })
        },
        // 删除方法
        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作',
                this.delent
            )
        },
        //删除回调
        delent () {
            this.$Ajax
                .httpGet({
                    url: '/outer/supplier/delete',
                    params: {
                        id: this.billid
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.replace('/supplierbePutinstorage')
                })
        },
        // 撤回
        withdrawChange () {
            this.clientPop('info', '是否确认撤回', this.callbackWithdraw)
        },
        // 撤回确认回调
        async callbackWithdraw () {
            let { code } = await examine.undoAudit({
                billId: this.id, //单据id
                billType: '6047', //单据类型
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            })
            if (code == 200) {
                showSuccessPop('撤回成功')
                // 返回列表
                this.cancel()
            } else {
                showSuccessPop('撤回失败')
            }
        },
        // 作废
        toVoidChange () {
            this.clientPop('info', '是否确认作废', this.callback)
        },
        // 作废确认回调
        async callbacks () {
            // 客户端弹窗弹出本地页面
            const auditParams = JSON.parse(localStorage.vuex).auditParams
            openAppClient('/nullifyDialog', '单据作废原因', async () => {
                showLoading()
                await toVoid({
                    billId: this.billid, //单据id
                    billType: '6047', //单据类型
                    nullifyCreated: '',
                    nullifyCreator: '',
                    nullifyCreatorId: '',
                    nullifyDescription: auditParams.nullifyDescription,
                    nullifyReason: auditParams.nullifyReason
                })
                    .catch(() => {
                        this.clientPop('suc', '作废失败')
                    })
                hideLoading()
            })
        },
        // 获取按钮状态
        getCurrentUnitInfo () {
            examine
                .getCurrentUnitInfo({
                    billId: this.id,
                    billType: 6047,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.withdrawChange() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.toVoidChange() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
